/**
* @Description: 客户管理(客户)-新增
* @author  tangbin
* @date 2023/4/18
*/
<template>
  <div class="mh100">
    <div class="page-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="88px">
        <div class="split-content-info" :style="{minHeight: height + 'px'}">
          <!-- 标题 -->
          <div class="split-content-title clearfix">
            <div class="split-title">
              <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
              <span style="display: inline-block; color: #333333; font-size: 16px;">新增客户</span>
            </div>
          </div>
          <el-row>
            <el-col :span="6">
              <el-form-item label="客户名称:" prop="name">
                <el-input
                  placeholder="请输入"
                  v-model="form.name"
                  maxlength="50"
                  size="small"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户类型:" prop="type" label-width="92px">
                <!-- 客户类型，这里只有单位和个人 -->
                <el-select v-model="form.type" placeholder="请选择" size="small" style="width:100%">
                  <el-option
                    v-for="item in dict.type.basic_data_tenant_customer_type"
                    v-if="item.value == 'COMPANY' || item.value == 'PERSON'"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 做正则 支持手机和固话 -->
              <el-form-item label="联系电话:" prop="telephone" label-width="92px">
                <!-- <el-popover
                  placement="top"
                  width="240"
                  trigger="hover"
                  content="如: 021-31654029或13800000000"
                >
                  <img
                    :src="hintIcon"
                    class="hint-icon"
                    slot="reference"
                    style="position: absolute; left: -23px; top: 0px"
                  />
                </el-popover> -->
                <!-- @blur="phoneMobileValidate(form.telephone, false)" -->
                <el-input
                  placeholder="请输入"
                  v-model="form.telephone"
                  maxlength="13"
                  size="small"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户联系人:" prop="contactName" label-width="94px">
                <el-input
                  placeholder="请输入"
                  v-model="form.contactName"
                  maxlength="50"
                  size="small"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="联系人电话:" prop="contactPhone" label-width="98px">
                <!-- <el-popover
                  placement="top"
                  width="240"
                  trigger="hover"
                  content="如: 021-31654029或13800000000"
                >
                  <img
                    :src="hintIcon"
                    class="hint-icon"
                    slot="reference"
                    style="position: absolute; left: -23px; top: 0px"
                  />
                </el-popover> -->
                <!-- @blur="phoneMobileValidate(form.contactPhone, true)" -->
                <el-input
                  placeholder="请输入"
                  v-model="form.contactPhone"
                  maxlength="13"
                  size="small"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否记账:" prop="accounting" label-width="92px">
                <el-select v-model="form.accounting" placeholder="请选择" size="small" style="width:100%">
                  <el-option
                    v-for="item in bookkeepingOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="折扣:" prop="discount" label-width="94px">
                <el-input
                  placeholder="请输入"
                  v-model="form.discount"
                  maxlength="50"
                  size="small"
                  @blur="checkDiscount(form, $event)"
                  oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                >
                <span slot="suffix" style="font-size: 12px; color: #333; line-height: 32px">%</span>
              </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户状态:" prop="status" label-width="92px">
                <el-select v-model="form.status" placeholder="请选择" size="small" style="width:100%">
                  <el-option
                    v-for="item in dict.type.basic_data_tenant_customer_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="地址:" prop="address">
            <el-input v-model="form.address" :autosize="{ minRows: 3, maxRows: 12}" type="textarea" placeholder="请输入内容" maxlength="200" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input v-model="form.remark" :autosize="{ minRows: 5, maxRows: 12}" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit></el-input>
          </el-form-item>
        </div>
      </el-form>


      <div class="h84_line"></div>
      <div class="bottom-btn">
        <div class="bottom-locate" >
          <el-button type="default" @click="cancel">取消</el-button>
          <el-button type="primary" :loading="saveloading" @click="save">确认</el-button>
        </div>
      </div>

    </div>
  </div>
</template>


<script>
import {getTimeSeconds} from '@/utils/index.js'
import hintIcon from '@/assets/images/hinticon.png'
import {validTelephone, validPhone, validataTelAndPhoneNew, validataTelAndPhones} from '@/utils/validate.js'
import {tenantCustomerAdd} from '@/api/basic/tenantCustomer.js'

export default {
  name: 'CustomersManageAdd',
  dicts: ['basic_data_tenant_customer_type', 'basic_data_tenant_customer_status'],  // 客户类型 客户状态
  data() {
    // 验证手机和座机
    const validateMobile = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error("请输入电话"));
      } else if (!validTelephone(value)) {
        callback(new Error("请输入正确格式的电话"));
      } else {
        callback();
      }
    };
    const validateTMobile = (rule, value, callback) => {
      if (value == undefined || value.length == 0) {
        // callback(new Error("请输入管理员手机号"));
        callback();
      } else if (!validTelephone(value)) {
        callback(new Error("请输入正确格式的电话"));
      } else {
        callback();
      }
    };
    return {
      hintIcon, //提示icon
      mountedTime: undefined, // mounted时间
      activatedTime: undefined, // activated时间
      height: 626,
      saveloading: false, // 点击确认旋转轮
      isThan: false,
      bookkeepingOptions: [{label: '是', value: 'Y'}, {label: '否', value: 'N'}], // 是否记账 N否；Y是
      form: {
        name: undefined, // 客户名称
        type: undefined, // 客户类型--仅支持个人和单位
        telephone: undefined, // 联系电话 -- 支持座机和手机号
        contactName: undefined, // 客户联系人
        contactPhone: undefined, // 联系人电话
        accounting: 'Y', // 是否记账 -- 默认是
        discount: undefined, // 折扣
        status: 'ENABLE', // 客户状态 -- 默认生效
        address: undefined, // 地址
        remark: undefined, // 备注
      },
      rules: {
        name: [
          {required: true, message: "请输入客户名称", trigger: "blur"}
        ],
        type: [
          {required: true, message: "请选择客户类型", trigger: "change"}
        ],
        telephone: [
          {required: true, message: "请输入联系电话", trigger: "blur"},
          {validator: validateMobile, trigger: 'blur'}
        ],
        contactPhone: [
          {required: false, message: "请输入联系电话", trigger: "blur"},
          {validator: validateTMobile, trigger: 'blur'}
        ],
        accounting: [
          {required: true, message: "请选择是否记账", trigger: "change"}
        ],
        status: [
          {required: true, message: "请选择客户状态", trigger: "change"}
        ],
      },
    }
  },
  mounted() {
    this.mountedTime = new Date();
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
  },
  activated() {
    this.activatedTime = new Date();
    let seconds = getTimeSeconds(this.mountedTime, this.activatedTime);
    if (seconds >= 1) {
      // this.getCustomerGoodsOrgs();
      // this.getTypeAndClassInfos();
    }
    
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
  },
  methods: {
    tableHeight() {
      this.$nextTick(() => {
        let height = document.body.clientHeight - 90 - 40;// - 62 - 20;
        // 查询表单高度
        let s_height = 0;
        // 按钮容器高度
        // let btns_height = document.getElementById('comTabel').clientHeight;
        // 计算表格的高度
        this.height = height - s_height - 20 - 44;
      });
    },

    /**
     * 联系人电话验证 - 手机号
     * @param {*} phone 
     */
    contactPhoneValidate(phone) {
      // console.log('phone=', phone);
      if (!validPhone(phone)) {
        this.$modal.msgError('请输入正确的电话!');
      }
    },

    /**
     * 判断固话手机号(固定电话或者手机号)
     * @param {*} phone 
     * @param {*} isEmpty true表示，phone 空的时候不做判断
     */
     phoneMobileValidate(phone, isEmpty) {
      // console.log('phone=', phone, '; isEmpty=', isEmpty);
      if (isEmpty && (phone == undefined || phone == null || phone == '' || (phone && phone.length == 0))) {
        return false;
      }
      if (!validataTelAndPhones(phone)) {
        this.$modal.msgError('请输入正确的电话!');
        return true;
      }
      return false;
    },

    /**
     * 输入折扣校验
     */
    checkDiscount(row, event) {
      this.isThan = false;
      row.discount = event.target.value;
      if (row.discount && row.discount.length > 0 && Number(row.discount) > 100) {
        this.$modal.msgWarning('折扣不能大于100！');
        row.discount = undefined;
        this.isThan = true;
        return;
      }
    },

    cancel() {
      const obj = { path: "/basicData/customersManage" };
      this.$tab.closeOpenPage(obj);
    },

    save() {
      if (this.isThan) { // 折扣
        return;
      }

      // if (this.form.contactPhone && this.form.contactPhone.length > 0) {
      //   return;
      // }
      // this.$modal.msgSuccess('添加客户成功！');
      // return;
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.saveloading = false;
          return;
        }
        this.saveloading = true;
        tenantCustomerAdd(this.form).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess('添加客户成功！');
            this.cancel();
          } else {
            this.$modal.msgError('添加客户失败！');
          }
          this.saveloading = false;
        }).catch(err => {
          this.saveloading = false;
        });
      });
    },

  },
}
</script>

<style lang="scss" scoped>
</style>